package com.sukaiyi.giteeideaplugin.mainwindow;

import cn.hutool.json.JSONObject;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.ui.AnimatedIcon;
import com.sukaiyi.giteeideaplugin.utils.IdeaUIUtils;
import com.sukaiyi.giteejavaapi.common.Gitee;
import com.sukaiyi.giteejavaapi.common.Params;
import com.sukaiyi.giteejavaapi.http.model.HttpResponse;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Optional;

public class ForkRepoWindow extends DialogWrapper {

    private JPanel content;
    private JBLabel stateLabel;
    private JBLabel messageLabel;
    private AnimatedIcon animatedIcon;

    public ForkRepoWindow(JSONObject repo) {
        super(true);
        setTitle(repo.getStr("name"));
        init();
        messageLabel.setVisible(false);
        Params params = Params.create()
                .set("owner", repo.getByPath("namespace.path", String.class))
                .set("repo", repo.getStr("path"));
        Gitee.getInstance().invoke("postV5ReposOwnerRepoForks", params).whenComplete((httpResponse, throwable) -> {
            animatedIcon.suspend();
            animatedIcon.setVisible(false);
            if (throwable != null) {
                throwable.printStackTrace();
                stateLabel.setText("Failed");
                stateLabel.setForeground(JBColor.RED);
                messageLabel.setVisible(true);
                messageLabel.setText(throwable.getMessage());
                return;
            }
            if (!httpResponse.success()) {
                stateLabel.setText("Failed");
                stateLabel.setForeground(JBColor.RED);
                String message = Optional.of(httpResponse).map(HttpResponse::asJSONObject).map(e -> e.getStr("message")).orElse("unknown error");
                messageLabel.setVisible(true);
                messageLabel.setText(message);
                return;
            }
            stateLabel.setText("Success");
            stateLabel.setForeground(JBColor.BLACK);
            repo.compute("forks_count", (key, old) -> {
                int oldInt = Optional.ofNullable(old).map(e -> (Integer) e).orElse(0);
                return oldInt + 1;
            });
        });
    }

    public void createUIComponents() {
        animatedIcon = IdeaUIUtils.createBigProgressIcon();
        animatedIcon.resume();
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        return content;
    }

    @Nullable
    @Override
    protected String getDimensionServiceKey() {
        return this.getClass().getName();
    }

    @NotNull
    @Override
    protected Action[] createActions() {
        return new Action[0];
    }
}
